package com.huai.jt1078.config;


import com.huai.jt1078.entity.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常拦截器
 * @Author: huai
 * @Date: 2020/10/15 17:56
 */
@ControllerAdvice
@Slf4j
public class ExceptionAdvice {

    /**
     * 错误异常拦截
     * @return
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResultVO<Object> exception(RuntimeException exception){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);
        log.error(sw.toString());
        return ResultVO.fail(exception.getMessage());
    }


    /**
     * 错误异常拦截
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultVO<Object> exception(Exception exception){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);
        log.error(sw.toString());
        return ResultVO.fail(exception.getMessage());
    }

    /**
     * 参数异常拦截
     * @return
     */
    @ResponseBody
    @ExceptionHandler({MethodArgumentNotValidException.class,
            BindException.class,
            HttpMessageNotReadableException.class,
            MethodArgumentTypeMismatchException.class
    })
    public ResultVO<Object> methodArgumentNotValidException(Exception exception){
        return ResultVO.fail(exception.getMessage());
    }
}
